/*
 * qcarpcdialog.cpp - elements GUI for qcarpc
 *
 * Copyright (C) 2010-2011 Serge Begger
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "qcarpcdialog.h"

myProgressbar::myProgressbar(QWidget *parent, QString text) :
    QWidget(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);
    setGeometry(QRect(200, 250, 400, 120));
    centralWidget = new QWidget(this);
    frame = new QFrame(centralWidget);
    frame->setGeometry(QRect(1, 1, 398, 118));
    frame->setFrameShape(QFrame::WinPanel);
    frame->setFrameShadow(QFrame::Plain);
    label = new QLabel(frame);
    label->setGeometry(QRect(10, 10, 371, 51));
    label->setWordWrap(true);
    QFont font;
    font.setPointSize(15);
    font.setBold(true);
    label->setFont(font);
    label->setText(text);
    label->setAlignment(Qt::AlignCenter);
    hProgressBar = new QProgressBar(frame);
    hProgressBar->setGeometry(QRect(10, 70, 371, 41));
    hProgressBar->setStyleSheet(QString::fromUtf8(""));
    hProgressBar->setValue(0);
    hProgressBar->setAlignment(Qt::AlignCenter);
    hProgressBar->setTextVisible(false);
    hProgressBar->setInvertedAppearance(false);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateSlider()));
    hide();
    LRValue = 1;
 }

myProgressbar::~myProgressbar()
{
    if(!timer->isActive()){
        timer->stop();
    }
}

void myProgressbar::setText(QString text)
{
    label->setText(text);
}

void myProgressbar::start()
{
    show();
    repaint();
    if(!timer->isActive())
         timer->start (10);
}

void myProgressbar::stop()
{
    hide();
    if(!timer->isActive()){
        timer->stop();
    }
    hProgressBar->setValue(0);
}

void myProgressbar::updateSlider()
{
    int currValue = hProgressBar->value();
    if (LRValue == -1)
    {
        currValue += LRValue;
        if (currValue < 0)
        {
            LRValue = 1;
            currValue = 0;
            hProgressBar->setInvertedAppearance(false);
        }
    } else {
        currValue += LRValue;
        if (currValue > 99)
        {
            LRValue = -1;
            currValue = 99;
            hProgressBar->setInvertedAppearance(true);
        }
    }
    hProgressBar->setValue(currValue);
}

numPanel::numPanel(QWidget *parent, bool freqpanel, QRect pangmtr) :
        QWidget(parent)
{
    typePanel = freqpanel;

    gmtr = pangmtr;

    freq = new QString("");

    if(typePanel)
        maxSymb = 6;
    else
        maxSymb = 12;

    formLayoutWidget = new QWidget(this);
    gridLayout = new QGridLayout(formLayoutWidget);

    QSignalMapper* mapper = new QSignalMapper( this );
    connect( mapper, SIGNAL(mapped(QString)), this, SLOT(pressedButtons(QString)) );

    QFont font1;
    font1.setPointSize(50);
    font1.setBold(true);
    font1.setFamily("SF Digital Readout");
    if (typePanel) {
        QFont fontH;
        fontH.setPointSize(18);
        fontH.setBold(true);

        helpLabel = new QLabel(formLayoutWidget);
        helpLabel->setFont(fontH);
        //helpLabel->setMinimumSize(170,60);
        gridLayout->addWidget(helpLabel, 0, 0, 1, 6);
    }

    QSize buttSize(80,80);

    num1Button = new QPushButton("1",formLayoutWidget);
    num1Button->setMinimumSize(buttSize);
    num1Button->setFont(font1);
    num1Button->setFocusPolicy(Qt::NoFocus);
    mapper->setMapping( num1Button, "1" );
    connect( num1Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num1Button, 1, 0, 1, 2);

    num2Button = new QPushButton("2",formLayoutWidget);
    num2Button->setMinimumSize(buttSize);
    num2Button->setFocusPolicy(Qt::NoFocus);
    num2Button->setFont(font1);
    mapper->setMapping( num2Button, "2" );
    connect( num2Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num2Button, 1, 2, 1, 2);

    num3Button = new QPushButton("3",formLayoutWidget);
    num3Button->setMinimumSize(buttSize);
    num3Button->setFocusPolicy(Qt::NoFocus);
    num3Button->setFont(font1);
    mapper->setMapping( num3Button, "3" );
    connect( num3Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num3Button, 1, 4, 1, 2);

    num4Button = new QPushButton("4",formLayoutWidget);
    num4Button->setMinimumSize(buttSize);
    num4Button->setFocusPolicy(Qt::NoFocus);
    num4Button->setFont(font1);
    mapper->setMapping( num4Button, "4" );
    connect( num4Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num4Button, 2, 0, 1, 2);

    num5Button = new QPushButton("5",formLayoutWidget);
    num5Button->setMinimumSize(buttSize);
    num5Button->setFocusPolicy(Qt::NoFocus);
    num5Button->setFont(font1);
    mapper->setMapping( num5Button, "5" );
    connect( num5Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num5Button, 2, 2, 1, 2);

    num6Button = new QPushButton("6",formLayoutWidget);
    num6Button->setMinimumSize(buttSize);
    num6Button->setFocusPolicy(Qt::NoFocus);
    num6Button->setFont(font1);
    mapper->setMapping( num6Button, "6" );
    connect( num6Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num6Button, 2, 4, 1, 2);

    num7Button = new QPushButton("7",formLayoutWidget);
    num7Button->setMinimumSize(buttSize);
    num7Button->setFocusPolicy(Qt::NoFocus);
    num7Button->setFont(font1);
    mapper->setMapping( num7Button, "7" );
    connect( num7Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num7Button, 3, 0, 1, 2);

    num8Button = new QPushButton("8",formLayoutWidget);
    num8Button->setMinimumSize(buttSize);
    num8Button->setFocusPolicy(Qt::NoFocus);
    num8Button->setFont(font1);
    mapper->setMapping( num8Button, "8" );
    connect( num8Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num8Button, 3, 2, 1, 2);

    num9Button = new QPushButton("9",formLayoutWidget);
    num9Button->setMinimumSize(buttSize);
    num9Button->setFocusPolicy(Qt::NoFocus);
    num9Button->setFont(font1);
    mapper->setMapping( num9Button, "9" );
    connect( num9Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num9Button, 3, 4, 1, 2);

    num0Button = new QPushButton("0",formLayoutWidget);
    num0Button->setMinimumSize(buttSize);
    num0Button->setFocusPolicy(Qt::NoFocus);
    num0Button->setFont(font1);
    mapper->setMapping( num0Button, "0" );
    connect( num0Button, SIGNAL(clicked()), mapper, SLOT(map()) );
    gridLayout->addWidget(num0Button, 4, 2, 1, 2);

    if(typePanel){
        numAsButton = new QPushButton(".",formLayoutWidget);
        mapper->setMapping( numAsButton, "." );
        connect( numAsButton, SIGNAL(clicked()), mapper, SLOT(map()) );
        numNoButton = new QPushButton("OK",formLayoutWidget);
        connect( numNoButton, SIGNAL(clicked()), this, SLOT(closeNumPanel()));        
    } else {
        numAsButton = new QPushButton("*",formLayoutWidget);
        mapper->setMapping( numAsButton, "*" );
        connect( numAsButton, SIGNAL(pressed()), mapper, SLOT(map()) );
        connect( numAsButton, SIGNAL(pressed()), this, SLOT(numAs()) );
        numNoButton = new QPushButton("#",formLayoutWidget);
        mapper->setMapping( numNoButton, "#" );
        connect( numNoButton, SIGNAL(pressed()), mapper, SLOT(map()) );
    }
    numAsButton->setMinimumSize(buttSize);
    numAsButton->setFont(font1);
    numAsButton->setFocusPolicy(Qt::NoFocus);
    numNoButton->setMinimumSize(buttSize);
    numNoButton->setFont(font1);
    numNoButton->setFocusPolicy(Qt::NoFocus);

    gridLayout->addWidget(numAsButton, 4, 0, 1, 2);
    gridLayout->addWidget(numNoButton, 4, 4, 1, 2);

    if(typePanel)
        this ->setVisible(false);
    else
        this->setGeometry(gmtr);
}

numPanel::~numPanel() {}

void numPanel::onShow()
{
    if (!this->isVisible())
    {
        this->setVisible(true);
        freq->clear();
        animation = new QPropertyAnimation(this, "geometry");
        animation->setDuration(200);
        animation->setStartValue(QRect(gmtr.x(), gmtr.y(), 0, 0));
        animation->setEndValue(gmtr);
        animation->start();
    }
}

void numPanel::offShow()
{
    if (this->isVisible())
    {
        animation = new QPropertyAnimation(this, "geometry");
        animation->setDuration(200);
        animation->setStartValue(gmtr);
        animation->setEndValue(QRect(gmtr.x(), gmtr.y(), 0, 0));
        connect(animation, SIGNAL(finished()), this , SLOT(animFinished()));
        animation->start();
    }
}

void numPanel::animFinished()
{
    this->setVisible(false);
    emit endPutFreq();
}

void numPanel::numAs()
{
    QTimer::singleShot(600, this, SLOT(endTimer()));
}

void numPanel::endTimer()
{
    if (numAsButton->isDown()){
        freq->clear();
        pressedButtons("+");
        emit putFreq();
    }
}

void numPanel::pressedButtons(QString num)
{
    freq->append(num);
    if (freq->size() > maxSymb) {
        freq->clear();
        freq->append(num);
    }
    emit putFreq();
}

void numPanel::closeNumPanel()
{
    offShow();
}


myMessage::myMessage(QWidget * parent) :
        QWidget(parent)
{
    result = false;
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowModality(Qt::WindowModal);
    setGeometry(QRect(140,160,520, 260));
    setAttribute(Qt::WA_DeleteOnClose, false);

    frame = new QFrame(this);
    frame->setGeometry(QRect(0, 0, 520, 260));
    frame->setFrameShape(QFrame::WinPanel);
    frame->setFrameShadow(QFrame::Plain);

    labelIcon = new QLabel(frame);
    labelIcon->setGeometry(QRect(10, 10, 51, 61));

    labelText = new QLabel(frame);
    labelText->setGeometry(QRect(80, 10, 431, 151));
    labelText->setScaledContents(true);
    labelText->setAlignment(Qt::AlignCenter);
    labelText->setWordWrap(true);
    QFont font;
    font.setPointSize(20);
    font.setBold(true);
    font.setWeight(75);
    labelText->setFont(font);

    ok_button = new QPushButton(frame);
    ok_button->setGeometry(QRect(220, 160, 90, 90));
    QIcon icon;
    icon.addFile(QString::fromUtf8(":/buttons/res/button_ok.png"), QSize(), QIcon::Normal, QIcon::Off);
    ok_button->setIcon(icon);
    ok_button->setIconSize(QSize(80, 80));

    cancel_button = new QPushButton(frame);
    cancel_button->setGeometry(QRect(270, 160, 90, 90));
    QIcon icon1;
    icon1.addFile(QString::fromUtf8(":/buttons/res/button_cancel.png"), QSize(), QIcon::Normal, QIcon::Off);
    cancel_button->setIcon(icon1);
    cancel_button->setIconSize(QSize(80, 80));

    cancel_button->setVisible(false);

    connect(ok_button, SIGNAL(pressed()),this,SLOT(ok_button_pressed()));
    connect(cancel_button, SIGNAL(pressed()),this,SLOT(cancel_button_pressed()));

    eventLoop = new QEventLoop(this);
    setHidden(true);
}

void myMessage::exec(int type, QString text)
{
    result = false;
    switch(type)
    {
    case 0:
        labelIcon->setPixmap(QPixmap(QString::fromUtf8(":/buttons/res/dialog-error.png")));
        break;
    case 1:
        labelIcon->setPixmap(QPixmap(QString::fromUtf8(":/buttons/res/dialog-information.png")));
        break;
    case 2:
        labelIcon->setPixmap(QPixmap(QString::fromUtf8(":/buttons/res/dialog-warning.png")));
        break;
    case 3:
        labelIcon->setPixmap(QPixmap(QString::fromUtf8(":/buttons/res/dialog-question.png")));
        ok_button->setGeometry(QRect(170, 160, 90, 90));
        cancel_button->setVisible(true);
        break;
    }
    labelText->setText(text);
    setHidden(false);
    eventLoop->exec();
}

void myMessage::ok_button_pressed()
{
    if (eventLoop->isRunning())
        eventLoop->exit();
    result = true;
    setHidden(true);
}

void myMessage::cancel_button_pressed()
{
    if (eventLoop->isRunning())
        eventLoop->exit();
    setHidden(true);
}

gslider::gslider(QWidget *parent, bool horizontal) :
    QFrame(parent)
{
    isHorizontal = horizontal;
    this->setFrameShape(QFrame::NoFrame);
    currValue = 0;
    minValue = 0;
    maxValue = 100;
}

gslider::~gslider()
{
}

void gslider::paintEvent(QPaintEvent *)
{
    if (isHorizontal) {
        paintTriangle();
        paintLine();
    } else {
        paintBar();
        paintGrid();
    }
}

void gslider::paintBar()
{
    int x,w,h, lengthBar;
    lengthBar = 0;
    x = this->x();
    w = this->width(); h = this->height(); //ширина / выcота
    QPainter painter(this);
    painter.setWindow(this->geometry());
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QColor(67,171,165));
    if ((maxValue >= 0 && minValue >= 0) || (maxValue >= 0 && minValue <= 0))
        lengthBar = h * (minValue-currValue)/(minValue-maxValue);
    if (maxValue <= 0 && minValue <= 0)
        lengthBar = h * (maxValue-currValue)/(maxValue-minValue);
    QRectF bar(x, h - lengthBar ,  w , lengthBar);
    painter.drawRoundRect(bar, 1);
}

void gslider::paintTriangle()
{
    int x,y,w,h, lengthTr, heightTr;
    lengthTr = 0; heightTr = 0;
    x = this->x(); y = this->y();
    w = this->width(); h = this->height(); //ширина / выcота
    QPainter painter(this);
    painter.setWindow(this->geometry());
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QColor(255,109,0));
    if ((maxValue >= 0 && minValue >= 0) || (maxValue >= 0 && minValue <= 0)) {        
        lengthTr = w * (minValue-currValue)/(minValue-maxValue);
        heightTr = h * (minValue-currValue)/(minValue-maxValue);
    }
    if (maxValue <= 0 && minValue <= 0) {       
        lengthTr = w * (maxValue-currValue)/(maxValue-minValue);
        heightTr = h * (maxValue-currValue)/(maxValue-minValue);
    }

    QPointF points[3] = {
        QPointF(x , y + h),
        QPointF(x + lengthTr , y + h ),
        QPointF(x + lengthTr, y + h - heightTr)
    };
    painter.drawConvexPolygon(points, 3);
}

void gslider::paintGrid()
{
    int x,y,w,h;
    x = this->x(); y = this->y();
    w = this->width(); h = this->height(); //ширина / выcота
    QPainter painter(this);
    painter.setWindow(this->geometry());
    painter.setRenderHint(QPainter::Antialiasing);
    QColor penColor = this->palette().background().color();
    painter.setPen(QPen(penColor, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));

    int numLinesH = h/5;
    int numLinesV = w/5;

    for (int i = 1; i <= numLinesH+1; i++)
    {
        painter.drawLine(x, y+(5*i), x+w, y+(5*i));
    }

    for (int i = 1; i <= numLinesV+1; i++)
    {
        painter.drawLine(x+(5 * i), y, x+(5*i), y+h);
    }

}

void gslider::paintLine()
{
    int x,y,w,h;
    x = this->x(); y = this->y();
    w = this->width(); h = this->height(); //ширина / выcота
    QPainter painter(this);
    painter.setWindow(this->geometry());
    painter.setRenderHint(QPainter::Antialiasing);
    QColor penColor = this->palette().background().color();
    painter.setPen(QPen(penColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));

    //int numLinesH = h/5;
    int numLinesV = w/10;

//    for (int i = 1; i <= numLinesH+1; i++)
//    {
//        painter.drawLine(x, y+(5*i), x+w, y+(5*i));
//    }

    for (int i = 1; i <= numLinesV+1; i++)
    {
        painter.drawLine(x+(10 * i), y, x+(10*i), y+h);
    }

}

void gslider::setValue(double value)
{
    currValue = value;
    update();
    return;
}

void gslider::setMaxValue(double max)
{
    maxValue = max;
}

void gslider::setMinValue(double min)
{
    minValue = min;
}

double gslider::value()
{
    return currValue;
}

double gslider::maximum() {
    return maxValue;
}

double gslider::minimum() {
    return minValue;
}

qcarpclog::qcarpclog(QObject *parent) :
    QObject(parent)
{
    logfile = new QFile(QDir::homePath()+"/qcarpc.log");
    if(logfile->size() > 10000000) {
        logfile->resize(0);
        if (logfile->open(QIODevice::Append | QIODevice::Text)) {
            QTextStream out(logfile);
            out << "log:logfile big - is rezet";
            out << "\n";
            logfile->close();
        }
    }
}

qcarpclog::~qcarpclog() {
    if (logfile->isOpen())
        logfile->close();
}

void qcarpclog::append(QString module, QString text) {
    if (logfile->open(QIODevice::Append | QIODevice::Text)) {
        QTextStream out(logfile);
        out << module << ":" ;
        out << QDateTime::currentDateTime().toString("dd.MMMM.yyyy HH:mm");
        out <<  ":" << text;
        out << "\n";
        logfile->close();
    }
}
